package util.mib;

import model.MibNode;
import util.common.StringUtils;

import java.util.*;

public class MibUtils {
    /**
     * 根据oid集合生成多棵oid树，通过name连接
     * @param mibNodeList
     * @return
     */
    public static List<MibNode> GenerateMibTreesByName(List<MibNode> mibNodeList) {

        List<MibNode> forest = new LinkedList<>();
        if (mibNodeList.size() == 0)
        {
            return new LinkedList<>();
        }

        Map<Integer, Map<String, MibNode>> levelNameNodeMap  = new HashMap<>();
        int level;

        // 把所有节点按层级分组，每组通过索引去除相同名字的节点。
        Map<String, MibNode> nameNodeMap;
        for (MibNode node : mibNodeList) {
            level = node.level;
            if (levelNameNodeMap.containsKey(level)) {
                nameNodeMap = levelNameNodeMap.get(level);
            }else {
                nameNodeMap = new HashMap<>();
                levelNameNodeMap.put(level, nameNodeMap);
            }
            if (!levelNameNodeMap.containsKey(node.name)){
                nameNodeMap.put(node.name, node);
            }
        }

        Integer[] levels = levelNameNodeMap.keySet().toArray(new Integer[levelNameNodeMap.size()]);
        Arrays.sort(levels);

        // 构建树
        for (int i = levels.length - 1; i > 0; i--) {
            level = levels[i];
            Map<String, MibNode> parentMap = levelNameNodeMap.get(level - 1);
            Collection<MibNode> children = levelNameNodeMap.get(level).values();
            children.forEach(child -> {
                if (parentMap.containsKey(child.parentName)) {
                    if (!parentMap.get(child.parentName).addChild(child)) {
                        System.out.println(child.name +  "无法成为" + child.parentName + "的子节点，oid不匹配。" +
                                "\nchild.oid = " + child.oid + "" +
                                "\nparent.oid = " + parentMap.get(child.parentName).oid);
                    }
                } else {
                    forest.add(child);
                }// 如果匹配不到父节点，该子节点单独形成森林
            });
        }

        forest.addAll(levelNameNodeMap.get(levels[0]).values()); // 把等级最低的的节点列表加进森林。
        MibFormatUtils.sortMibTree(forest);
        return forest;
    }

    /**
     * 根据给定的oid值搜索mib树(森林)
     * 警告：剪枝或合并过的oid树搜索结果可能异常！
     * @param modules
     * @param oid
     * @return 若找到：返回该oid节点，若有子树，则包含子树；否则：返回null
     */
    public static MibNode searchModuleInTree(List<MibNode> modules, String oid) {
        if (StringUtils.isNullOrWhiteSpace(oid))
        {
            throw new IllegalArgumentException("oid不能为空。");
        }
        String[] strs = StringUtils.splitRemoveEmpty(oid, "\\.");
        int level = strs.length;
        int node = Integer.parseInt(strs[level - 1]);
        return doSearchModuleInTree(modules, oid, level, node);
    }

    /**
     * 递归遍历OID树
     * @param modules
     * @param oid
     * @param level
     * @param node
     * @return
     */
    private static MibNode doSearchModuleInTree(List<MibNode> modules, String oid, int level, int node) {
        for (MibNode module : modules) {
            if (module.level < level && oid.startsWith(module.oid + ".")) { // 当前节点的层级数少于被搜索节点，且前半部分与被搜索节点匹配
                MibNode searchNode = doSearchModuleInTree(module.children, oid, level, node);  // 递归搜索子节点
                if (searchNode != null) {
                    return searchNode;
                }
            }
            else if (module.level == level && module.node == node)
            {
                return module;
            }
        }

        return null;
    }



}
